{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Conversation with CodeAct Agent\n",
    "\n",
    "CodeAct agent is an agent that not only chats but also writes and executes Python code for you.\n",
    "More details can be found in the project's related [github repo](https://github.com/xingyaoww/code-act). \n",
    "\n",
    "In the following CodeAct agent example, we demonstrate another method of empowering the agent with the capability to invoke tools, specifically by directly providing the agent with the corresponding code for the tools and then allowing the agent to utilize them independently.\n",
    "Interm of tool usage, ReAct agent also enables the agent to use tools to solve problems, but in a different way. You can refer to the [ReAct agent](https://github.com/modelscope/agentscope/blob/main/examples/conversation_with_react_agent/main.ipynb) example for more details and compare the two.\n",
    "\n",
    "## Prerequisites\n",
    "\n",
    "- Follow [READMD.md](https://github.com/modelscope/agentscope) to install AgentScope. We require the lastest version, so you should build from source by running `pip install -e .` instead of intalling from pypi. \n",
    "- Prepare a model configuration. AgentScope supports both local deployed model services (CPU or GPU) and third-party services. More details and example model configurations please refer to our [tutorial](https://modelscope.github.io/agentscope/en/tutorial/203-model.html).\n",
    "\n",
    "## Note\n",
    "- The example is tested with the following models. For other models, you may need to adjust the prompt.\n",
    "    - qwen-max"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "YOUR_MODEL_CONFIGURATION_NAME = \"{YOUR_MODEL_CONFIGURATION_NAME}\"\n",
    "\n",
    "YOUR_MODEL_CONFIGURATION = {\n",
    "    \"model_type\": \"xxx\", \n",
    "    \"config_name\": YOUR_MODEL_CONFIGURATION_NAME\n",
    "    \n",
    "    # ...\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 1: Initalize the AgentScope environment\n",
    "\n",
    "Here we initialize the AgentScope environment by calling the `agentscope.init` function. The `model_configs` parameter specifies the path to the model configuration file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import agentscope\n",
    "\n",
    "agentscope.init(model_configs=YOUR_MODEL_CONFIGURATION)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 2: Set up the code for tool usage, and init the CodeAct Agent.\n",
    "\n",
    "Here, we provide the CodeAct agent with the interactive code that the agent can use during the conversation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "from loguru import logger\n",
    "from codeact_agent import CodeActAgent\n",
    "\n",
    "from agentscope.message import Msg\n",
    "\n",
    "YOUR_BING_API_KEY = \"xxx\" # fill in your bing api key here\n",
    "\n",
    "example_code = f\"\"\"\n",
    "from agentscope.service import bing_search\n",
    "import os\n",
    "\n",
    "api_key = \"{YOUR_BING_API_KEY}\"\n",
    "\n",
    "def search(question: str):\n",
    "    return bing_search(question, api_key=api_key, num_results=3).content\n",
    "\"\"\"\n",
    "\n",
    "import nest_asyncio\n",
    "nest_asyncio.apply()\n",
    "agent = CodeActAgent(\n",
    "    name=\"assistant\",\n",
    "    model_config_name=YOUR_MODEL_CONFIGURATION_NAME,\n",
    "    example_code=example_code\n",
    ")\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 3: Ask the CodeAct-agent to execute tasks\n",
    "\n",
    "Here, we ask the CodeAct-agent with the example question in the ReAct Paper: `\"Aside from the Apple Remote, what other device can control the program Apple Remote was originally designed to interact with?\"` as follows, same as in the [ReAct-agent]((https://github.com/modelscope/agentscope/blob/main/examples/conversation_with_react_agent/main.ipynb)) example."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2024-05-17 10:58:04.214 | INFO     | agentscope.models.model:__init__:201 - Initialize model by configuration [dashscope_chat-qwen-max]\n",
      "2024-05-17 10:58:04.215 | INFO     | agentscope.utils.monitor:register:417 - Register metric [qwen-max.call_counter] to SqliteMonitor with unit [times] and quota [None]\n",
      "2024-05-17 10:58:04.218 | INFO     | agentscope.utils.monitor:register:417 - Register metric [qwen-max.prompt_tokens] to SqliteMonitor with unit [token] and quota [None]\n",
      "2024-05-17 10:58:04.220 | INFO     | agentscope.utils.monitor:register:417 - Register metric [qwen-max.completion_tokens] to SqliteMonitor with unit [token] and quota [None]\n",
      "2024-05-17 10:58:04.222 | INFO     | agentscope.utils.monitor:register:417 - Register metric [qwen-max.total_tokens] to SqliteMonitor with unit [token] and quota [None]\n",
      "user: Example Code excuted: Excution Successful:\n",
      " Execution Output:\n",
      "[]\n",
      "user: Aside from the Apple Remote, what other device can control the program Apple Remote was originally designed to interact with?\n",
      "assistant: [execute]\n",
      "search_result = search(\"Aside from the Apple Remote, what other device can control the program Apple Remote was originally designed to interact with?\")\n",
      "search_result\n",
      "[/execute]\n",
      "user: Excution Successful:\n",
      " Execution Output:\n",
      "[\"[{'title': 'Multi-Agent实践第4期：智能体的“想”与“做”-ReAct Agent - 知乎',\\n  'link': 'https://zhuanlan.zhihu.com/p/689675968',\\n  'snippet': 'Other than the Apple Remote, you can use a supported TV or receiver remote, a network-based remote for home-control systems, an infrared remote (commonly known as a universal remote), or other Apple devices like an iPhone or iPad to control the Apple'},\\n {'title': 'REACT：在语言模型中协同推理与行动，使其能够解决各种 ...',\\n  'link': 'https://blog.csdn.net/fogdragon/article/details/132550968',\\n  'snippet': 'Q：Aside from the Apple Remote, what other device can control the program Apple Remote was originally designed to intect with? 除了苹果遥控器之外，还有哪些设备可以控制最初设计用于连接的苹果遥控器所配合的程序？'},\\n {'title': '《ReAct: SYNERGIZING REASONING AND ACTING IN ...',\\n  'link': 'https://www.cnblogs.com/LittleHann/p/17541295.html',\\n  'snippet': 'Aside from the Apple Remote, what other devices can control the program Apple Remote was originally designed to interact with?'}]\"]\n",
      "assistant: According to the search results, aside from the Apple Remote, you can use the following devices to control the program it was designed to interact with:\n",
      "\n",
      "1. A supported TV or receiver remote.\n",
      "2. A network-based remote for home-control systems.\n",
      "3. An infrared remote (universal remote).\n",
      "4. Other Apple devices such as an iPhone or iPad.\n",
      "\n",
      "These alternatives allow for similar control functionality as the Apple Remote.\n"
     ]
    }
   ],
   "source": [
    "mss = Msg(\n",
    "    name=\"user\", \n",
    "    content=\"Aside from the Apple Remote, what other device can control the program Apple Remote was originally designed to interact with?\", \n",
    "    role=\"user\"\n",
    ")\n",
    "logger.chat(mss)\n",
    "answer_mss1 = agent(mss)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The CodeAct agent successfully use the given search tool functions and return the answer accordingly. This demonstrates the wide range of usage of agent with coding abilities.\n",
    "Feel free to explore the Agent by yourself!"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "datajuicer",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
